<script setup lang="ts">
defineOptions({
  name: "Authconfig",
  inheritAttrs: false,
});
import { GetTeacherInfo } from "@/api/course";
import { getTeacherRoleTypes } from "@/api/role";
import { translateTagDictI18n } from "@/utils/i18n";
import {
  AddLinkTeacher,
  DirectAddTeacher,
  deleteTeacherRole,
  changeTeacherRole,
} from "@/api/teacher";
import { AddLinkTeacherData, AddTeacherData } from "@/api/teacher/types";
import { useAppStore } from "@/store/modules/app";
import { FormRules } from "element-plus";
import { useCourseStore } from "@/store/modules/course";

const courseStore = useCourseStore();
const courseId = ref();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { course_effective_time } = proxy?.useDict("course_effective_time"); // 有效时间
// 汉堡
const appStore = useAppStore();
// 表格加载
const tabLoading = ref(false);
// 当前激活的标签页
const activeName = ref("link");
// 角色
const roleOptions = ref<OptionType[]>([]);
// 创建表单
const linkRef = ref(ElForm);
// 邀请链接
const link = ref("");
// 表单信息
const AddRefFrom = ref(ElForm);
// 信息总数
const TeacherList = ref<GroupedData[]>();
// 请求链接数据
const AddData = reactive<AddTeacherData>({
  flag: 0,
});
// 请求链接数据
const GetLinkeData = reactive<AddLinkTeacherData>({
  // 初始化
  effectiveTime: 3, // 初始化有效时间
});
// 创建弹窗组件
const dialog = reactive<DialogOption>({
  visible: false,
});
// 打开弹窗
function openDialog() {
  dialog.visible = true;
  dialog.title = "添加成员信息";
}
// 关闭弹窗
function closeDialog() {
  dialog.visible = false;
}
//表单规则
const rulesfrom = ref<FormRules>({
  effectiveTime: [
    { required: true, message: "请选择链接有效时间", trigger: "blur" },
  ],
  roleId: [{ required: true, message: "请选择角色权限", trigger: "blur" }],
});
// 直接添加表单规则
const Addrules = ref<FormRules>({
  flag: [{ required: true, trigger: "blur", message: "请选择添加方式" }],
  roleId: [{ required: true, trigger: "blur", message: "请选择角色" }],
  keywords: [{ required: true, trigger: "blur", validator: phoneValidator }],
});

// 封装手机号验证规则函数
function isvalidPhone(phone: string) {
  const reg = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/;
  return reg.test(phone);
}
// 手机号校验器函数 phoneValidator
function phoneValidator(_rule: any, value: string, callback: any) {
  if (!value && AddData.flag == 0) {
    callback(new Error("请填写电话号码"));
  } else if (!isvalidPhone(value) && AddData.flag == 0) {
    //判断用户输入的值是否符合规则
    callback(new Error("请填写正确的11位手机号码"));
  } else if (!value && AddData.flag == 1) {
    callback(new Error("请填写工号"));
  } else {
    callback();
  }
}
// 保存数据
interface UserData {
  nickname: string;
  userId: number;
  roleName: string;
  roleId: number;
  courseName: string;
}
// 分组类型
interface GroupedData {
  name: string;
  data: UserData[];
}
// 处理数据函数
function groupDataByRoleName(data: UserData[]): GroupedData[] {
  const groupedData: { [roleName: string]: UserData[] } = {};
  // 分组数据
  data.forEach((item) => {
    if (!groupedData[item.roleName]) {
      groupedData[item.roleName] = [];
    }
    groupedData[item.roleName].push(item);
  });

  // 构造最终结果数组
  const result: GroupedData[] = Object.keys(groupedData).map((roleName) => {
    return {
      name: roleName,
      data: groupedData[roleName],
    };
  });

  return result;
}
// 直接添加学生信息函数
function AddTeacherInfo() {
  AddRefFrom.value.validate((valid: boolean) => {
    if (valid) {
      DirectAddTeacher(AddData, courseId.value)
        .then(() => {
          ElMessage.success("已添加到课程中!");
          handleQuery(); //更新
          closeDialog();
        })
        .catch((err) => {
          console.log(err);
        });
    }
  });
}
// 直接添加用户信息函数
function deleteTeacher(id: number) {
  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteTeacherRole(id, courseId.value)
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery(); //更新
        closeDialog();
      })
      .catch((err) => {
        console.log(err);
      });
  });
}
// 定义一个方法，处理链接邀请的表单提交事件
function submitLink() {
  linkRef.value.validate((valid: boolean) => {
    if (valid) {
      AddLinkTeacher(GetLinkeData, courseId.value)
        .then(({ data }) => {
          link.value = data;
          ElMessage.success("链接已生成");
        })
        .catch((err) => {
          console.log("err", err);
        });
    }
  });
}
// 查询列表
function handleQuery() {
  tabLoading.value = true;
  GetTeacherInfo(courseId.value)
    .then(({ data }) => {
      TeacherList.value = groupDataByRoleName(data);
    })
    .finally(() => {
      tabLoading.value = false;
    });
  getTeacherRoleTypes().then(({ data }) => {
    roleOptions.value = data;
  });
}
function change(e: any, id: number) {
  changeTeacherRole(e, id, courseId.value)
    .then(() => {
      ElMessage.success("切换角色权限成功");
      handleQuery();
    })
    .catch(() => {
      handleQuery();
    });
}

onMounted(() => {
  courseId.value = courseStore.courseId;
  appStore.sidebar.opened = false;
  handleQuery();
});
</script>

<template>
  <div>
    <!-- 添加班级信息 -->
    <el-dialog
      v-model="dialog.visible"
      class="dialog"
      :title="dialog.title"
      width="400px"
      append-to-body
      @close="closeDialog"
    >
      <el-tabs
        v-model="activeName"
        tab-position="top"
        class="profile-tabs"
        style="margin-top: -15px"
        :stretch="true"
      >
        <el-tab-pane
          :label="$t('authconfig.LinkEinladung')"
          name="link"
          class="profile-tabs-pane"
        >
          <!-- 链接邀请面板 -->
          <el-divider class="enter-x">{{
            $t("authconfig.Einladungslink")
          }}</el-divider>
          <el-form
            ref="linkRef"
            label-position="left"
            style="margin-top: 10px"
            :model="GetLinkeData"
            :rules="rulesfrom"
          >
            <!-- 链接 -->
            <el-form-item>
              <el-input v-model="link" disabled />
              <div style="opacity: 0.6; font-size: 8px">
                {{
                  $t(
                    "authconfig.EinladungslinkLäuft" +
                      GetLinkeData.effectiveTime
                  )
                }}
              </div>
            </el-form-item>
            <!-- 有效时间 -->
            <el-form-item
              :label="$t('authconfig.WirksameZeit') + '：'"
              prop="effectiveTime"
            >
              <el-select v-model="GetLinkeData.effectiveTime">
                <el-option
                  v-for="dict in course_effective_time"
                  :key="dict.value"
                  :label="
                    translateTagDictI18n('course_effective_time', dict.label)
                  "
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
            <!--选择班级 -->
            <el-form-item
              :label="$t('authconfig.BerechtigungenAuswählen') + '：'"
              prop="roleId"
            >
              <el-select v-model="GetLinkeData.roleId">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="$t('authconfig.' + item.label)"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-button v-throttle="submitLink" class="elbtn" type="primary">{{
              $t("authconfig.LinkGenerieren")
            }}</el-button>
            <el-button v-copy="link" class="elbtn" type="primary">{{
              $t("authconfig.Linkkopieren")
            }}</el-button>
          </el-form>
        </el-tab-pane>
        <!--  直接添加面板 -->
        <el-tab-pane :label="$t('authconfig.DirektHinzufügen')" name="add">
          <el-divider class="enter-x">{{
            $t("authconfig.MitgliederEinladen")
          }}</el-divider>
          <el-form
            ref="AddRefFrom"
            :model="AddData"
            :rules="Addrules"
            label-position="left"
            style="margin-top: 10px"
          >
            <el-form-item
              :label="$t('authconfig.MethodeHinzufügen') + '：'"
              prop="flag"
            >
              <el-radio-group v-model="AddData.flag">
                <el-radio :label="0">{{
                  $t("authconfig.Mobiltelefonnummer")
                }}</el-radio>
                <el-radio :label="1">{{ $t("authconfig.JobID") }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              :label="$t('authconfig.BerechtigungenAuswählen') + '：'"
              prop="roleId"
            >
              <el-select v-model="AddData.roleId" style="width: 100%">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="$t('authconfig.' + item.label)"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="
                AddData.flag === 0
                  ? $t('authconfig.Mobiltelefonnummer') + '：'
                  : $t('authconfig.JobID') + '：'
              "
              prop="keywords"
              style="width: 100%"
            >
              <el-input
                v-model="AddData.keywords"
                :placeholder="
                  AddData.flag === 0
                    ? $t('authconfig.BitteTelefonnummer')
                    : $t('authconfig.BitteJobnummer')
                "
              />
            </el-form-item>
            <el-button v-throttle="AddTeacherInfo" type="primary">{{
              $t("authconfig.Hinzufügenbestätigen")
            }}</el-button>
          </el-form>
        </el-tab-pane>
        <!-- 二维码添加面板 -->
        <el-tab-pane :label="$t('authconfig.EinladungQRCode')" name="qrcode">
          <el-divider class="enter-x">{{
            $t("authconfig.QRCodeAnzumelden")
          }}</el-divider>
          <el-row style="maring-left: -10px; maring-right: -10px">
            <!-- <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
              <LoginFormTitle style="width: 100%" />
            </el-col> -->
            <el-col :span="24" style="padding-left: 10px; padding-right: 10px">
              <el-card class="mb-10px text-center" shadow="hover">
                <svg-icon
                  icon-class="daiwanshan"
                  style="width: 50%; height: 50%"
                />
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-card class="protector" shadow="never">
      <template #header>
        <div class="c-header">
          <el-text size="large">{{ $t("authconfig.VerwaltunGungen") }}</el-text>
          <el-button
            v-throttle="openDialog"
            v-hasPerm="['courseinfo:authconfig:add']"
            type=""
            plain
            style="color: var(--el-color-primary)"
          >
            <svg-icon
              icon-class="classadd"
              style="margin-right: 5px; font-size: 24px"
            />
            {{ $t("authconfig.MitgliederEinladen") }}
          </el-button>
        </div>
      </template>
      <el-table
        v-for="(item, index) in TeacherList"
        :key="index"
        v-loading="tabLoading"
        :data="item.data"
      >
        <el-table-column
          :label="`${$t('authconfig.' + item.name)}(${item.data.length})`"
          width="800"
        >
          <template #default="scop">
            &nbsp;&nbsp;&nbsp;&nbsp;{{ scop.row.nickname }}
            <el-tag class="c-tag" plain size="small">{{
              $t("authconfig." + scop.row.roleName)
            }}</el-tag>
            <el-tag
              v-if="scop.row.roleId === 3"
              class="c-tag"
              type="success"
              plain
              size="small"
              >{{ $t("authconfig.Ichselbst") }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template #default="scop">
            <el-button
              v-if="scop.row.roleId === 3"
              type=""
              plain
              style="color: var(--el-color-primary)"
            >
              <svg-icon
                icon-class="admin_r"
                style="margin-right: 5px; font-size: 20px"
              ></svg-icon>
              {{ $t("authconfig.Administratoren") }}</el-button
            >
            <el-select
              v-if="scop.row.roleName !== '创建者'"
              v-model="scop.row.roleId"
              tag-type="success"
              class="m-2"
              style="width: 100px"
              @change="(e) => change(e, scop.row.userId)"
            >
              <el-option
                v-for="roleItem in roleOptions"
                :key="roleItem.value"
                :label="$t('authconfig.' + roleItem.label)"
                :value="roleItem.value"
              />
            </el-select>
            <el-button
              v-if="scop.row.roleName !== '创建者'"
              v-throttle="() => deleteTeacher(scop.row.userId)"
              v-hasPerm="['courseinfo:authconfig:delete']"
              type="danger"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.protector {
  margin: 2em;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.1);
}

.c-tag {
  margin-right: 0.33em;
}

.c-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 1em;
}
</style>
